/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: YKH
 * Date: 2022-04-05
 * Time: 14:26
 */
//线程安全问题 举例
    //使用两个线程将 count 变量 从0 加到 10w

public class Test04 {
   static class Counter {
        public int count = 0;
        public void add () {
            count++;
        }
    }
    static Counter con = new Counter();
    public static void main(String []args) {
        //线程1
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50000; i++) {
                   con.add ();
                }
            }
        });
        //线程2
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50000; i++) {
                    con.add ();
                }
            }
        });
        t1.start();
        t2.start();
        //阻塞线程，等t1 t2线程都都运行结束
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //输出结果
        System.out.println(con.count);
    }
}
